<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >
                新增角色
              </el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="list">
              <el-table-column label="序号" type="index" width="120" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <!-- 操作 -->
              <el-table-column #default="{row}" label="操作">
                <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
              </el-table-column></el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件  @current-change -------》 currentPage 改变时会触发 -->
              <el-pagination layout="prev,pager,next" :total="page.total" :page-size="page.pagesize" @current-change="currentChange" />
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <el-alert
              title="公司信息无法修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="fromData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="fromData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="fromData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="fromData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="titleText" :visible="showDialog" @close="btnCancel">
        <el-form v-if="showDialog" ref="roleforms" :model="roleform" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleform.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleform.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取 消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确 定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 权限分配 -->
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!-- 权限是一颗树 -->
        <!-- 将数据绑定到组件上 -->
        <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
        <!-- id作为唯一标识 -->
        <!-- 这里并没有 v-model 的双向绑定
        无论设置绑定还是获取绑定数据, 都靠函数
        对象中的那个值作为记录的标识, 需要 node-key 进行设定 -->
        <el-tree
          ref="permTree"
          :data="permData"
          :props="{label: 'name'}"
          :default-expand-all="true"

          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCompanyInfo, getRoleList, delRole, getRoleDetail, updateRole, addRole, assignPermission } from '@/api/setting'
import { getPermissionList } from '@/api/permission' // 获取权限列表
// 筛选二级
import { Fixthebrokenarray } from '@/utils'
export default {
  data() {
    return {
      // 对话框
      showDialog: false,
      showPermDialog: false, // 权限分配
      permData: [], // 权限列表
      userId: '',
      // 对话框
      roleform: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      },
      fromData: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      // 翻页设定对象
      page: {
        // 显示当前页
        page: 1,
        // 每页显示数
        pagesize: 2,
        // 总页数
        total: 0
      },
      // 创建一个空数组保存获取的数据
      list: []
    }
  },
  computed: {
    titleText() {
      return this.roleform.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    // 权限分配
    async assignPerm(id) {
      this.userId = id
      this.permData = Fixthebrokenarray(await getPermissionList(), '0')
      const { permIds } = await getRoleDetail(id)
      console.log(permIds)
      this.showPermDialog = true
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },
    btnPermCancel() {
      // 1. 清空数据
      this.$refs.permTree.setCheckedKeys([])
      this.showPermDialog = false
    },
    // 确定按钮
    async btnPermOK() {
      const permIds = this.$refs.permTree.getCheckedKeys()
      const id = this.userId
      await assignPermission({
        id,
        permIds
      })
      // 提醒用户
      this.$message.success('修改成功')
      // 关闭弹窗
      this.showPermDialog = false
    },
    // 公司信息
    async getCompanyInfo() {
      // console.log(this.$store)
      this.fromData = await getCompanyInfo(this.$store.state.user.userInfo.companyId)
    },
    // 角色列表
    async getRoleList() {
      // 获取到两个数据 通过解构获取
      // total 总页数
      const { rows, total } = await getRoleList(this.page)
      // console.log(rows, total)
      this.list = rows
      // console.log('list', this.list)

      this.page.total = total
    },
    // 分页
    currentChange(Newpege) {
      this.page.page = Newpege
      this.getRoleList()
    },
    // 根据id删除角色
    async delRole(id) {
      try {
        console.log(id)
        // 二次校验
        await this.$confirm('是否确认删除该角色？')

        // 发送请求
        await delRole(id)
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        // 提醒用户
        this.$message.success('删除成功')
        // 重新获取数据
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    btnCancel() {
      // 清空表单
      this.roleform = {
        name: '',
        description: ''
      }
      // 清理验证
      this.$refs.roleforms.resetFields()
      // 关闭弹窗
      this.showDialog = false
    },
    // 确认按钮
    async btnOK() {
      // 验证
      await this.$refs.roleform.validate()
      // 发送请求
      if (this.fromData.id) {
      // 编辑
        await updateRole(this.fromData)
      } else {
      // 新增
        await addRole(this.fromData)
      }
      // 提示用户
      this.$message.success('操作成功')
      // 关闭弹窗
      this.showDialog = false
      // 重新加载数据
      this.getRoleList()
    },
    // 角色数据回显
    async editRole(id) {
      this.showDialog = true
      this.roleform = await getRoleDetail(id)
      // console.log(await getRoleDetail(id))
    }
  }

}
</script>

<style>

</style>
